import axios from 'axios'
import Cache from './cache'
import Util from './util'
import Bridge from './bridge'
import Storage from './storage'
import { Toast } from 'vant'
import { NOTICE_CODE, APP_FUN, APP_LISTENER } from './enums'


axios.defaults.withCredentials = true // 允许 cors 请求带 cookie
axios.defaults.timeout = 3e4;

const toast = message => {
    Toast({
        message,
        duration: 2000,
        forbidClick: true
    })
}
/**
 * ⚠️ 固定参数
 * @param {默认} config 
 */
const setHeader = config => {
    let userData = Storage.get('ML_USER_INFO');
    let headerObj = {};
    if (userData) {
        headerObj = {
            token: userData.token
        };  
    }
    

    let paramsName = config.method == 'post' ? 'data' : 'params';
    if (config[paramsName]) {
        headerObj = {
            ...headerObj,
        }
    }
    for (let k in headerObj) {
        if (headerObj[k]) config.headers[k] = headerObj[k];
    }
}
/**
 * ⚠️ 跨域传参
 * @param {默认} config 
 */
const setAuthorization = config => {
    let user = Cache.user.get(), authorization = {};
    if (user) {
        for (let k in user) authorization[k] = user[k];
        config.headers['Authorization'] = Util.setQueryStringParams(authorization, ';');
    }
}

const reLogin = message => {
    if (Storage.get('ML_USER_INFO')) {
        Storage.remove('token');     
        Storage.clear();     
    }
    if (message) toast(message)
    // 清除缓存
    // do...
}

const getCurrentTime = () => {
    var now = new Date(+Cache.custom.get('server_diff_time') + (+new Date));
    var hour = now.getHours();
    if (hour.toString().length < 2) {
        hour = "0" + hour;
    }
    var minute = now.getMinutes();
    if (minute.toString().length < 2) {
        minute = "0" + minute;
    }
    return hour + ':' + minute
}

axios.interceptors.request.use(
    config => {
        setHeader(config);
        // setAuthorization(config);
        return config;
    },
    error => Promise.reject(error)
)

axios.interceptors.response.use(
    res => {
        let result = res.data;
        let {
            status,
            code,
            message,
            msg
        } = result;
        if (code == 200 || status == 200) {
            return result;
        } else if (code == 5001 || status == 5001) {
            reLogin(message);
            var Api = Vue.prototype.$api;
            window.location.replace(Api.wechatRedirect+'?redirect_uri='+encodeURIComponent('https://healthc.mirror-networks.com/h5/dietitian/#/login?redirect='+ window.location.href))
            return;
            
        } else {
            try {
                let errInfo = result.debug.exception;
                if (errInfo.includes('Request method') && errInfo.includes('not supported')) toast(NOTICE_CODE[405]);
                log(2, errInfo);
            } catch (error) {
                log(1, message || msg);
            }
            return result;
        }
    },
    err => {
        let {
            message,
            response
        } = err;
        log(err);
        let text = '';
        if (response && response.status) {
            text = response.status >= 500 ? NOTICE_CODE[500] : NOTICE_CODE[httpCode];
        } else {
            if (message === 'Network Error') {
                // 大部分异常会走这里，上层没有抛出具体的错误分析
                text = NOTICE_CODE[1003];
                Bridge._js2(APP_FUN[5001]);
                Bridge._2js(APP_LISTENER[5001], status => {
                    if(status == 3) {
                        text = NOTICE_CODE[1001];
                        toast(text);
                    }
                })
            } else if (message.includes('timeout')) {
                text = NOTICE_CODE[1002]
            } else {
                text = NOTICE_CODE[1003]
            }
        }
        toast(text);
        
        throw new Error(text);
    }
)

export default {
    get: (url, params) => {
        return new Promise(async (resolve, reject) => {
            axios.get(url, {
                params
            }).then(res => {
                res && resolve(res)
            }).catch(err => {
                reject(err)
            })
        })
    },
    post: (url, data) => {
        return new Promise(async (resolve, reject) => {
            axios.post(url, data).then(res => {
                res && resolve(res)
            }).catch(err => {
                reject(err)
            })
        })
    },
}